<template>
  <section class="todoapp">
    <!-- 除了驼峰, 还可以使用-转换链接 -->
    <TodoHeader @add='addFn' :list='list' @checked='checkedFn'></TodoHeader>
    <TodoMain :list='showList' @del='delFn'
    @change='changeFn'
    ></TodoMain>
    <TodoFooter :list='list' @clear='clearFn'
    :type='type'
    @changeTypeFn='changeTypeFn'></TodoFooter>
  </section>
</template>

<script>
// 1.0 样式引入
import "./styles/base.css"
import "./styles/index.css"
    
import TodoHeader from "./components/TodoHeader";
import TodoMain from "./components/TodoMain";
import TodoFooter from "./components/TodoFooter";


export default {
  components: {
    TodoHeader,
    TodoMain,
    TodoFooter,
  },
  data() {
    return {
      // 9.1取出本地存储数据渲染页面
      list:JSON.parse(localStorage.getItem('taskList')) || [],
      // 7 底部选项高亮 传给子组件
      type:'all' // all:全选 yes:已完成 no:未完成
    };
  },
  // 9本地存储
  watch:{
    list: {
      deep:true,
      handler(val) {
        localStorage.setItem('taskList',JSON.stringify(val))
      }
    }
  },
  computed:{
    // 7.1准备点击切换
    showList() {
      if(this.type =='yes'){
        return this.list.filter(item => item.isDone);
      }else if(this.type =='no') {
        return this.list.filter(item => !item.isDone);
      }else{
        return this.list
      }
    }
  },
  methods:{
    delFn(id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    // isDone取反
    changeFn(id) {
      const res = this.list.find(item => item.id ==id)
      res.isDone = !res.isDone
    },
    // 4.4接收Header组件传来的数据
    addFn(name) {
      this.list.push({
        id:this.list.length ? this.list.at(-1).id +1 : 100,
        name,
        isDone: false 
      })
    },
    //6.1 接收触发清空执行函数 保留item.isDone == false的任务
    clearFn() {
      this.list = this.list.filter(item => item.isDone == false)
    },
    // 7.5完成点击高亮效果
    changeTypeFn(type) {
      this.type = type
    },
    // 8.1
    checkedFn(val) {
      this.list.forEach(item => item.isDone=val)
    }
  }
};
</script>